package com.cy.pj.common.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {

    //has a
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        //1.获取连接对象
        try {
            conn = dataSource.getConnection();
            //2.创建Statement对象(负责发送sql-sql传送器)
            stmt = conn.createStatement();
            //3.发送sql
            String sql = "select * from tb_goods";
            rs = stmt.executeQuery(sql);
            //4.处理结果集
            List<Map<String, Object>> list = new ArrayList<>();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {//循环一次取一行,一行记录映射为一个map对象
                Map<String, Object> map = new HashMap<>();
//                map.put("id", rs.getInt(1));
//                map.put("name", rs.getString(2));
//                map.put("remark", rs.getString(3));
//                map.put("createdTime", rs.getTimestamp(4));
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));
                    String columnLabel = rsmd.getColumnLabel(i);
                    System.out.println("columnLabel = " + columnLabel);
                    Object object = rs.getObject(i);
                    System.out.println("object = " + object);
                }
                list.add(map);
                System.out.println("我存了啊！");
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            if (rs != null) try {
                rs.close();
            } catch (SQLException e) {
            }
            if (stmt != null) try {
                stmt.close();
            } catch (SQLException e) {
            }
            if (conn != null) try {
                conn.close();
            } catch (SQLException e) {
            }
        }
        return null;
    }
}
